package io.github.veigara.tcp.framework.metrics;

import io.github.veigara.tcp.framework.model.DeviceType;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 设备指标收集器
 */
@Component
public class DeviceMetricsCollector {
    private final MeterRegistry registry;
    private final ConcurrentHashMap<DeviceType, AtomicInteger> onlineDevices = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<DeviceType, Counter> connectionCounters = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<DeviceType, Counter> disconnectionCounters = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<DeviceType, Counter> messageCounters = new ConcurrentHashMap<>();

    public DeviceMetricsCollector(MeterRegistry registry) {
        this.registry = registry;
    }

    public void recordDeviceConnected(DeviceType deviceType) {
        AtomicInteger count = onlineDevices.computeIfAbsent(deviceType, type -> {
            AtomicInteger gauge = new AtomicInteger(0);
            Gauge.builder("devices.online", gauge, AtomicInteger::get)
                    .tag("type", deviceType.name())
                    .description("Number of online devices")
                    .register(registry);
            return gauge;
        });
        count.incrementAndGet();

        connectionCounters.computeIfAbsent(deviceType, type ->
                registry.counter("devices.connections", "type", deviceType.name())
        ).increment();
    }

    public void recordDeviceDisconnected(DeviceType deviceType) {
        AtomicInteger count = onlineDevices.get(deviceType);
        if (count != null) {
            count.decrementAndGet();
        }

        disconnectionCounters.computeIfAbsent(deviceType, type ->
                registry.counter("devices.disconnections", "type", deviceType.name())
        ).increment();
    }

    public void recordMessageReceived(DeviceType deviceType) {
        messageCounters.computeIfAbsent(deviceType, type ->
                registry.counter("messages.received", "type", deviceType.name())
        ).increment();
    }
}